package com.honghe.system.controller;

import java.util.List;
import java.io.IOException;
import java.io.File;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.honghe.common.annotation.Log;
import com.honghe.common.core.controller.BaseController;
import com.honghe.common.core.domain.AjaxResult;
import com.honghe.common.enums.BusinessType;
import com.honghe.system.domain.DebtInformation;
import com.honghe.system.service.IDebtInformationService;
import com.honghe.common.utils.poi.ExcelUtil;
import com.honghe.common.core.page.TableDataInfo;
import com.honghe.common.utils.file.FileUploadUtils;
import com.honghe.common.utils.file.FileUtils;
import com.honghe.common.config.RuoYiConfig;

/**
 * 债权转让Controller
 * 
 * @author xjw
 * @date 2025-04-22
 */
@RestController
@RequestMapping("/system/information")
public class DebtInformationController extends BaseController
{
    @Autowired
    private IDebtInformationService debtInformationService;

    /**
     * 查询债权转让列表
     */
    @PreAuthorize("@ss.hasPermi('system:information:list')")
    @GetMapping("/list")
    public TableDataInfo list(DebtInformation debtInformation)
    {
        startPage();
        List<DebtInformation> list = debtInformationService.selectDebtInformationList(debtInformation);
        return getDataTable(list);
    }

    /**
     * 导出债权转让列表
     */
    @PreAuthorize("@ss.hasPermi('system:information:export')")
    @Log(title = "债权转让", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DebtInformation debtInformation)
    {
        List<DebtInformation> list = debtInformationService.selectDebtInformationList(debtInformation);
        ExcelUtil<DebtInformation> util = new ExcelUtil<DebtInformation>(DebtInformation.class);
        util.exportExcel(response, list, "债权转让数据");
    }

    /**
     * 获取债权转让详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:information:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(debtInformationService.selectDebtInformationById(id));
    }

    /**
     * 新增债权转让
     */
    @PreAuthorize("@ss.hasPermi('system:information:add')")
    @Log(title = "债权转让", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DebtInformation debtInformation)
    {
        return toAjax(debtInformationService.insertDebtInformation(debtInformation));
    }

    /**
     * 修改债权转让
     */
    @PreAuthorize("@ss.hasPermi('system:information:edit')")
    @Log(title = "债权转让", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DebtInformation debtInformation)
    {
        return toAjax(debtInformationService.updateDebtInformation(debtInformation));
    }

    /**
     * 删除债权转让
     */
    @PreAuthorize("@ss.hasPermi('system:information:remove')")
    @Log(title = "债权转让", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(debtInformationService.deleteDebtInformationByIds(ids));
    }
    
    /**
     * 上传文件
     */
    @PreAuthorize("@ss.hasPermi('system:information:edit')")
    @Log(title = "文件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 上传文件到 information 子目录
            String filePath = FileUploadUtils.upload(RuoYiConfig.getProfile() + "/information", file);
            
            // 文件信息格式为：原始文件名|存储路径
            String fileInfo = file.getOriginalFilename() + "|" + filePath;
            
            return AjaxResult.success("上传成功", fileInfo);
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }
    
    /**
     * 下载文件
     */
    @PreAuthorize("@ss.hasPermi('system:information:query')")
    @GetMapping("/download-file")
    public void downloadFile(@RequestParam("filePath") String filePath, HttpServletResponse response) throws IOException {
        try {
            logger.info("收到下载请求，原始路径: {}", filePath);
            
            // 构建完整路径
            String fullPath = "";
            
            // 检查是否包含年份日期格式，如2025/05/14/
            boolean isDatePath = filePath.matches(".*(20\\d{2}/\\d{2}/\\d{2}/).*");
            logger.info("是否为日期格式路径: {}", isDatePath);
            
            // 检查是否已经包含information目录
            if (filePath.startsWith("information/")) {
                fullPath = RuoYiConfig.getProfile() + "/" + filePath;
            } else if (isDatePath) {
                // 如果是日期格式的路径，直接添加到上传根路径
                fullPath = RuoYiConfig.getProfile() + "/information/" + filePath;
            } else {
                // 如果不包含information目录，添加
                fullPath = RuoYiConfig.getProfile() + "/information/" + filePath;
            }
            
            logger.info("构建的完整文件路径: {}", fullPath);
            
            File file = new File(fullPath);
            logger.info("文件是否存在: {}, 是否为文件: {}, 文件大小: {}", 
                file.exists(), file.isFile(), file.exists() ? file.length() : 0);
            
            if (!file.exists()) {
                logger.error("文件不存在: {}", fullPath);
                
                // 尝试其他可能的路径
                // 1. 尝试不带information的路径
                String alternatePath1 = RuoYiConfig.getProfile() + "/" + filePath;
                File alternateFile1 = new File(alternatePath1);
                logger.info("尝试备用路径1 (不带information): {}, 文件存在: {}", alternatePath1, alternateFile1.exists());
                
                // 2. 尝试直接使用日期格式路径
                String alternatePath2 = "";
                File alternateFile2 = null;
                if (isDatePath) {
                    // 如果是yyyy/MM/dd/filename.ext格式，尝试直接拼接到根目录
                    alternatePath2 = RuoYiConfig.getProfile() + "/" + filePath;
                    alternateFile2 = new File(alternatePath2);
                    logger.info("尝试备用路径2 (日期格式): {}, 文件存在: {}", alternatePath2, alternateFile2.exists());
                }
                
                if (alternateFile1.exists()) {
                    file = alternateFile1;
                    fullPath = alternatePath1;
                    logger.info("在备用路径1找到文件: {}", fullPath);
                } else if (alternateFile2 != null && alternateFile2.exists()) {
                    file = alternateFile2;
                    fullPath = alternatePath2;
                    logger.info("在备用路径2找到文件: {}", fullPath);
                } else {
                    response.setContentType("text/plain;charset=UTF-8");
                    response.getWriter().write("文件不存在或已被删除");
                    return;
                }
            }
            
            // 获取原始文件名
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            
            logger.info("准备下载文件: {}, 文件名: {}", fullPath, fileName);
            
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + 
                URLEncoder.encode(fileName, "UTF-8"));
            
            FileUtils.writeBytes(fullPath, response.getOutputStream());
            logger.info("文件下载成功: {}", fileName);
        } catch (Exception e) {
            logger.error("文件下载失败", e);
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("文件下载失败：" + e.getMessage());
        }
    }
}
